package com.jiahui.vote.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jiahui.vote.dao.VoteDao;
import com.jiahui.vote.entity.Vote;
import org.thymeleaf.util.StringUtils;

import java.util.Date;

@Service
public class VoteServiceImpl implements VoteService{
    @Autowired
    VoteDao voteDao;

    @Override
    public Vote[] getAllVotes() {
        Vote[] votes=voteDao.getAll();
        for (Vote vote:votes) {
            if(StringUtils.isEmpty(vote.getOption())){
                vote.setCountoption(null);
            }
            if(StringUtils.isEmpty(vote.getOption2())){
                vote.setCountoption2(null);
            }
            if(StringUtils.isEmpty(vote.getOption3())){
                vote.setCountoption3(null);
            }
            if(StringUtils.isEmpty(vote.getOption4())){
                vote.setCountoption4(null);
            }
            if(StringUtils.isEmpty(vote.getOption5())){
                vote.setCountoption5(null);
            }
            if(StringUtils.isEmpty(vote.getOption6())){
                vote.setCountoption6(null);
            }
            if(StringUtils.isEmpty(vote.getOption7())){
                vote.setCountoption7(null);
            }
        }
        return votes;
    }

    @Override
    public Vote getVoteById(int id) {
        Vote vote=voteDao.getOne(id);
        return vote;
    }

    @Override
    public boolean addVote(Vote vote) {
        Date date=new Date();
        vote.setDate(date);
        int result= voteDao.add(vote);
        return result>0?true:false;
    }

    @Override
    public boolean deleteVote(int id) {
        int result=voteDao.delete(id);
        return result>0?true:false;
    }

    @Override
    public boolean vote(int id, int which) {
        Vote vote=voteDao.getOne(id);
        switch(which){
            case 1 :
                vote.setCountoption(vote.getCountoption()+1);//语句
                break; //可选
            case 2 :
                vote.setCountoption2(vote.getCountoption2()+1);//语句
                break; //可选
            case 3 :
                vote.setCountoption3(vote.getCountoption3()+1);//语句
                break; //可选
            case 4 :
                vote.setCountoption4(vote.getCountoption4()+1);//语句
                break; //可选
            case 5 :
                vote.setCountoption5(vote.getCountoption5()+1);//语句
                break; //可选
            case 6 :
                vote.setCountoption6(vote.getCountoption6()+1);//语句
                break; //可选
            case 7 :
                vote.setCountoption7(vote.getCountoption7()+1);//语句
                break; //可选
        }

        int result=voteDao.update(vote);
        return result>0?true:false;
    }
}
